/*
 * @Author: Flora
 * @Descripttion: 
 * @Date: 2024-11-26 14:49:54
 * @LastEditors: Flora
 * @LastEditTime: 2025-08-07 13:15:49
 */
#import <Cordova/CDV.h>
#import "AliCloudMobile.h"
  
#import <AVKit/AVKit.h>
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonCrypto.h>
 

#import <ATAuthSDK/ATAuthSDK.h>
#import <ATAuthSDK/PNSReturnCode.h>
#import <YTXMonitor/YTXMonitor.h>
#import <YTXOperators/YTXOperators.h>

// 添加 languageInfo 属性声明
@interface AliCloudMobile ()
@property (nonatomic, strong) NSDictionary *languageInfo;
@end

@implementation AliCloudMobile
{
    NSString *webUrlStringUserAgreement;
    NSString *webUrlStringPrivacyAndChildrenPolicy;
}

static NSString* myAsyncCallBackId = nil;
static CDVPluginResult *pluginResult = nil;
static AliCloudMobile *selfplugin = nil;


- (void)pluginInitialize {
    webUrlStringUserAgreement = @"https://www.ruiquejia.com.cn/privacy-cn/user-agreement.html";
    webUrlStringPrivacyAndChildrenPolicy =  @"https://www.ruiquejia.com.cn/privacy-cn/privacyAndChildrenPolicy.html"; 
}

- (void)setAuthSDKInfo:(CDVInvokedUrlCommand *)command
{
    selfplugin = self;
    myAsyncCallBackId = command.callbackId;   
    NSString *info = [command.arguments objectAtIndex:0];
    NSLog(@"Setting Auth SDK Info: %@", info);

    // 如果有languageInfo参数，则设置
    if (command.arguments.count > 1) {
        self.languageInfo = [command.arguments objectAtIndex:1];
    }

    [[TXCommonHandler sharedInstance] setAuthSDKInfo:info complete:^(NSDictionary * _Nonnull resultDic) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resultDic];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)getLoginToken:(CDVInvokedUrlCommand *)command
{
    selfplugin = self;
    myAsyncCallBackId = command.callbackId;

    [self initOneKeyLoginBtn]; 
}

- (UIViewController*) topMostController
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}
 
- (void)initOneKeyLoginBtn {
    UIViewController *presentingController = [self topMostController];
    TXCustomModel *model = [self setupCustomModel];
    [[TXCommonHandler sharedInstance] getLoginTokenWithTimeout:5.0 controller:presentingController model:model complete:^(NSDictionary * _Nonnull resultDic) {
        NSString *resultCode = resultDic[@"resultCode"] ?: @"";
        NSString *msg = resultDic[@"msg"] ?: @"Unknown error occurred";
        NSString *token = resultDic[@"token"] ?: @"";

        NSDictionary *response;
        if ([resultCode isEqualToString:PNSCodeSuccess] ||
            [resultCode isEqualToString:PNSCodeLoginControllerPresentSuccess] ||
            [resultCode isEqualToString:PNSCodeLoginControllerClickLoginBtn] ||
            [resultCode isEqualToString:PNSCodeLoginControllerClickCheckBoxBtn] ||
            [resultCode isEqualToString:PNSCodeLoginControllerClickProtocol]) {
            response = @{@"msg": msg, @"code": resultCode, @"token": token};
        } else {
            response = @{@"msg": msg, @"code": resultCode};
        }
        [self sendCmd:response];

        if ([resultCode isEqualToString:PNSCodeSuccess] || [resultCode isEqualToString:PNSCodeLoginControllerClickChangeBtn]) {
            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
        }
    }];
}

- (void)accelerateLoginPage {
    @try {
        [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:3.0 complete:^(NSDictionary * _Nonnull resultDic) {
            NSString *resultCode = resultDic[@"resultCode"] ?: @"";
            NSString *msg = resultDic[@"msg"] ?: @"Unknown error occurred";
            NSString *token = resultDic[@"token"] ?: @"";

            NSDictionary *response;
            if ([resultCode isEqualToString:PNSCodeSuccess] ||
                [resultCode isEqualToString:PNSCodeLoginControllerPresentSuccess] ||
                [resultCode isEqualToString:PNSCodeLoginControllerClickLoginBtn] ||
                [resultCode isEqualToString:PNSCodeLoginControllerClickCheckBoxBtn] ||
                [resultCode isEqualToString:PNSCodeLoginControllerClickProtocol]) {
                response = @{@"msg": msg, @"code": resultCode, @"token": token};
            } else {
                response = @{@"msg": msg, @"code": resultCode};
            }

            [self sendCmd:response];
            [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
        }];
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occurred: %@, %@", exception.name, exception.reason);
        NSDictionary *errorDetails = @{
            @"error": @"Exception occurred",
            @"name": exception.name,
            @"reason": exception.reason
        };
        [self sendCmd:errorDetails];
        [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];
    }
}

- (TXCustomModel *)setupCustomModel {
    // [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil]; //关闭授权页面
    
    //自定义拉起授权页面
    TXCustomModel *model = [[TXCustomModel alloc] init];

    model.navIsHidden = NO;    // 设置导航栏是否隐藏。
    model.navBackImage  = [UIImage imageNamed:@"main_icon_nav_back_light"];
    model.navColor = UIColor.whiteColor;

    model.logoImage = [UIImage imageNamed:@"logo"]; // logo图片设置
    model.navTitle =  [[NSAttributedString alloc] initWithString:@"" attributes:@{NSForegroundColorAttributeName : UIColor.whiteColor,NSFontAttributeName : [UIFont systemFontOfSize:20.0]}];

    // 一键登录slogan文案 - 使用 languageInfo 中的值
    NSString *sloganText = @"本机号码可一键登录";
    NSString *loginBtnText = @"一键登录/注册";

    if (self.languageInfo) {
        if (self.languageInfo[@"sloganText"]) {
            sloganText = self.languageInfo[@"sloganText"];
        }
        if (self.languageInfo[@"loginButtonText"]) {
            loginBtnText = self.languageInfo[@"loginButtonText"];
        }
    }

    // 一键登录slogan文案
    model.sloganText = [[NSAttributedString alloc] initWithString:sloganText attributes:@{NSForegroundColorAttributeName : UIColor.blackColor,NSFontAttributeName : [UIFont systemFontOfSize:16.0]}];
    model.numberColor = UIColor.blackColor;
    model.numberFont = [UIFont systemFontOfSize:30.0];

    // 登录按钮 设置
    model.loginBtnText = [[NSAttributedString alloc] initWithString:loginBtnText attributes:@{  NSForegroundColorAttributeName : UIColor.whiteColor,NSFontAttributeName : [UIFont systemFontOfSize:20.0]}];
    model.loginBtnBgImgs = @[[UIImage imageNamed:@"login_btn_normal"],[UIImage imageNamed:@"login_btn_unable"],[UIImage imageNamed:@"login_btn_press"]];
    
    // 切换其他登录方式
    model.changeBtnIsHidden = YES;
    
    // 隐私政策
    model.privacyNavColor = UIColor.blackColor;
    model.privacyNavBackImage = [UIImage imageNamed:@"icon_nav_back_light"];
    model.privacyNavTitleFont = [UIFont systemFontOfSize:20.0];
    model.privacyNavTitleColor = UIColor.whiteColor;
    if(webUrlStringUserAgreement  != nil && webUrlStringPrivacyAndChildrenPolicy != nil){
        model.privacyOne = @[@"《用户服务协议》",webUrlStringUserAgreement];
        model.privacyTwo = @[@"《隐私政策、儿童隐私保护声明》",webUrlStringPrivacyAndChildrenPolicy];
    }

    model.privacyColors = @[UIColor.lightGrayColor,
                            [UIColor colorWithRed:255.0/255.0
                                    green:198.0/255.0
                                    blue:0.0/255.0
                                    alpha:1.0]];
    model.privacyAlignment = NSTextAlignmentCenter;
    model.privacyFont = [UIFont fontWithName:@"PingFangSC-Regular" size:13.0];
    model.privacyOperatorPreText = @"《";
    model.privacyOperatorSufText = @"》";
    model.checkBoxImages = @[[UIImage imageNamed:@"checkbox_unchecked"],[UIImage imageNamed:@"checkbox_checked"]];
    model.checkBoxIsHidden = NO;
    model.checkBoxWH = 17.0;
    model.prefersStatusBarHidden = NO;
    model.preferredStatusBarStyle = UIStatusBarStyleLightContent;
    model.presentDirection = PNSPresentationDirectionBottom;
     
    return model;
}

- (void)sendCmd : (NSDictionary *)msg {
    if(myAsyncCallBackId != nil)
    {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary: msg ];
        //将 CDVPluginResult.keepCallback 设置为 true ,则不会销毁callback
        [pluginResult  setKeepCallbackAsBool:YES];
        [selfplugin.commandDelegate sendPluginResult:pluginResult callbackId: myAsyncCallBackId];
    }
}

-(void)msgButtonClick{
    [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:nil];

    NSString *otherLoginType = @"切换到短信登录方式";

    if (self.languageInfo) {
        if (self.languageInfo[@"otherLoginType"]) {
            otherLoginType = self.languageInfo[@"otherLoginType"];
        }
    }

    NSDictionary *msgDict = @{
        @"status": @"1",
        @"message": otherLoginType
    };
    [self sendCmd:msgDict];
}

- (void)cancelLogin:(CDVInvokedUrlCommand *)command {
    [[TXCommonHandler sharedInstance] cancelLoginVCAnimated:YES complete:^{
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)accelerateLoginPage:(CDVInvokedUrlCommand *)command {
    NSInteger timeout = [[command.arguments objectAtIndex:0] integerValue];
    [[TXCommonHandler sharedInstance] accelerateLoginPageWithTimeout:timeout complete:^(NSDictionary * _Nonnull resultDic) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resultDic];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)checkEnvironment:(CDVInvokedUrlCommand *)command {
    // 移除未使用的变量
    [[command.arguments objectAtIndex:0] integerValue];
    [[TXCommonHandler sharedInstance] checkEnvAvailableWithAuthType:PNSAuthTypeVerifyToken complete:^(NSDictionary * _Nullable resultDic) {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resultDic];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}

- (void)isChinaMobile:(CDVInvokedUrlCommand *)command {
    BOOL isChinaMobile = [TXCommonUtils isChinaMobile];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isChinaMobile];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)isChinaTelecom:(CDVInvokedUrlCommand *)command {
    BOOL isChinaTelecom = [TXCommonUtils isChinaTelecom];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:isChinaTelecom];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)getCurrentCarrierName:(CDVInvokedUrlCommand *)command {
    NSString *carrierName = [TXCommonUtils getCurrentCarrierName];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:carrierName];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)simSupportedIsOK:(CDVInvokedUrlCommand *)command {
    BOOL simSupported = [TXCommonUtils simSupportedIsOK];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:simSupported];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)getUniqueID:(CDVInvokedUrlCommand *)command {
    NSString *uniqueID = [TXCommonUtils getUniqueID];
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:uniqueID];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)showAlertWithStr:(NSString *)str {
    UIViewController *presentingController = [self topMostController];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertVC addAction:sureAction];
    [presentingController presentViewController:alertVC animated:YES completion:nil];
}

@end